<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='800'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 4 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 20 }, sm: { span: 24 } }'
    >

      <a-form-item label='固件名称:' name='firmwareName'>
        <a-input v-model:value='form.firmwareName' placeholder='请输入固件名称' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item label='版本号:' name='firmwareVersion'>
        <a-input-number style="width:160px;" v-model:value='form.firmwareVersion' placeholder='请输入版本号' allow-clear autocomplete='off' />
      </a-form-item>

      <a-form-item v-if="!isUpdate" label='bin文件:' name='firmwareName'>
        <a-upload
          name="file"
          :multiple="false"
          :action="fileUploadUrl"
          :headers="headers"
          list-type="text"
          v-model:file-list="tempFileList['binFile']"
          @change="handleFileChange($event, 'binFile')"
        >
          <a-button>
            <upload-outlined />
            上传bin文件
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import {DevicePowerMonitorFirmwareApi} from "@/api/property/powermonitorclient/DevicePowerMonitorFirmwareApi";
import { FileUploadUrl as fileUploadUrlPrefix } from '@/api/system/operation/FileApi';
import { message } from 'ant-design-vue';
import {getToken} from "@/utils/token-util";

export default {
  name: 'DevicePowerMonitorFirmwareEdit',
  components: {
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  created() {
    if (this.data) {
      this.form = Object.assign({}, this.data);
      this.isUpdate = true;
    } else {
      this.form = {};
      this.isUpdate = false;
    }
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        firmwareName: [{ required: true, message: '请输入固件名称', type: 'string', trigger: 'blur' }],
        firmwareVersion: [{ required: true, message: '请输入版本号', type: 'number', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      fileUploadUrl: `/api${fileUploadUrlPrefix}?secretFlag=N&fileDir=device%2Fversion`,
      // 上传文件时候要带header
      headers: {
        Authorization: getToken()
      },
      // 临时存放文件列表（用来限制上传数量）
      tempFileList: {}
    };
  },
  methods: {
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2022/04/03 18:31
     */
    async save() {
      console.log(this.form);
      // 校验表单
      await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = DevicePowerMonitorFirmwareApi.edit(this.form);
      } else {
        result = DevicePowerMonitorFirmwareApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2022/04/03 18:31
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    /**
     * 上传文件改变时的状态
     *
     * @param info 组件回调原有参数
     * @param fieldCode 文件表单字段名称
     * @author xixiaowei
     * @date 2021/12/29 14:25:18
     */
    handleFileChange(info, fieldCode) {
      if (info.file.status === 'done') {
        // 设置临时fileList的值
        this.tempFileList[fieldCode] = [info.file];
        // 将文件属性名和文件编码存入数组中
        message.success(`${info.file.name} 图片上传成功`);
        // 设置表单对应的文件属性的值
        this.form['fileId'] = info.file.response.data.fileId;
        this.form['fileName'] = info.file.response.data.fileUrl;
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 图片上传失败`);
      }
    },
  }
};
</script>
